<template>
  <div>
      <el-page-header :icon="ArrowLeft">

          <template #title>
              <span @click="back">返回</span>
          </template>

          <template #content>
              <span class="fs-14"> 诊所管理 </span>
              <el-icon style="vertical-align: -3px;">
                  <Right />
              </el-icon>
              <span class="fs-14 cr-blue"> 诊所信息 </span>
          </template>
      </el-page-header>


      <!-- 新增表单 -->
      <el-form ref="ruleFormRef" :model="form" label-width="120px" class="mt-12" :rules="rules">
          <el-form-item label="诊所名称" prop="name">
              <el-input v-model="form.name" class="input-width" placeholder="请输入诊所名称" size="large"/>
          </el-form-item>
          <el-form-item label="诊所地址" prop="address">
              <el-input v-model="form.address" class="input-width"  placeholder="请输入诊所地址" size="large"/>
          </el-form-item>
          <el-form-item label="星级" prop="star">
              <el-select v-model="form.star" placeholder="请选择星级" class="input-width" size="large">
                  <el-option v-for="item in stars" :label="item.lable" :value="item.value" />
              </el-select>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" class="input-width" placeholder="请输入诊所联系电话" size="large"/>
          </el-form-item>
          <el-form-item label="营业时间" prop="date">
              <div class="input-width">
                  <el-date-picker format="YYYY-MM-DD" v-model="form.date" type="daterange" range-separator="至"
                      start-placeholder="请选择开店时间" end-placeholder="请选择闭店时间" size="large" />
              </div>
          </el-form-item>
          <el-form-item label="诊所特点" prop="desc">
              <el-input v-model="form.desc" type="textarea" size="large" placeholder="请准确填写诊所特色信息，包括服务项目，有助于患者更好的了解诊所，并进行就诊治疗，请准确填写诊所特色信息，包括服务项目，有助于患者更好的了解诊所，并进行就诊治疗"/>
              <p class="flth">还可输入 <span class="flth-n">{{ descRemain }}</span> 字</p>
          </el-form-item>


          <!-- 上传图片 -->
          <el-form-item label="添加照片">
              <el-upload class="avatar-uploader" action="http://127.0.0.1:4523/m1/2587975-0-default/upload"
                  :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" size="large">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                  </el-icon>
              </el-upload>
              
          </el-form-item>
          <p class="flth" style="margin-left: 120px ;margin-bottom: 25px;">还可上传 <span class="flth-n">{{ imgsRemain }}</span> 张</p>

          <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                  提交
              </el-button>
              <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
      </el-form>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue'
import { ArrowLeft, Right, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { useNavigate } from '../hooks'
import { useRoute } from 'vue-router'
import { clinicadd, clinicedit, cliniclist } from '../api'

// do not use same name with ref
const form = reactive({
  name: '',
  address: '',
  star: "",
  phone: '',
  date: [],
  desc: '',
  imgs: []
})


const navigator = useNavigate()
const navigateTo = (url: string) => {
  navigator.navigateTo(url)
}
const back = function () {
  console.log('back,....')
  navigator.back()
}

const route = useRoute()
const id = ref(route.query.id)

const stars = ref([{ value: 1, lable: "一星" }, { value: 2, lable: "二星" }, { value: 3, lable: "三星" }, { value: 4, lable: "四星" }, { value: 5, lable: "五星" }])

// 图片上传
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {

  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  form.imgs = response.data
}


const picWhiteList = ["image/jpeg", "image/png"]

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // if (rawFile.type !== 'image/jpeg') {
  if (picWhiteList.indexOf(rawFile.type) === -1) {
      ElMessage.error('Avatar picture must be JPG format!')
      return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('Avatar picture size can not exceed 2MB!')
      return false
  }
  return true
}


// 计算诊所特点还剩多少个字
const descRemain = computed(() => {
  return 800 - form.desc.length
})
// 计算还能上传多少张图片
const imgsRemain = computed(() => {
  return 5 - form.imgs.length
})


// 验证规则
const rules = reactive<FormRules>({
  name: [
      { required: true, message: '请输入诊所名称', trigger: 'blur' },
      { min: 3, max: 10, message: '诊所名称在3到10位之间', trigger: 'blur' },
  ],
  address: [
      { required: true, message: '请输入诊所地址', trigger: 'blur' }
  ],
  star: [
      { required: true, message: '请选择诊所星级', trigger: 'blur' }
  ],
  phone: [
      { required: true, message: '请输入诊所联系方式', trigger: 'blur' },
      { min: 11, max: 11, message: '手机号长度为11位', trigger: 'blur' },
  ],
  date: [
      { required: true, message: '请选择诊所营业时间', trigger: 'blur' },
  ],
  desc: [
      { required: true, message: '请输入诊所特点', trigger: 'blur' },
      { min: 1, max: 800, message: '诊所特点文本长度需要小于800字', trigger: 'blur' },
  ],
  imgs: [
      { required: false, message: '请选择图片', trigger: 'blur' },
      { min: 0, max: 5, message: '最多上传五张图片', trigger: 'blur' },
  ]
})

const ruleFormRef = ref<FormInstance>()

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(async()=>{
  resetForm()

  if(id.value){
    const res=await cliniclist({id:id.value})

    for(let key in res[0]){
      form[key]=res[0][key]
    }

    imageUrl.value=form.imgs[0]
  }
})

const submitForm = async (formEl: FormInstance | undefined) => {
  console.log("提交表单", formEl)
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
      if (valid) {
          form.date = form.date.map(d => {
              console.log(d)
              console.log(d.getTime())
              return d.getTime()
          })
          if(id.value){
            form.id=id.value
            const res=await clinicedit(form)
          }else{
            const res = await clinicadd(form)
          }
          // console.log('提交表单，把数据发送个接口!', form)
          
          navigateTo("/clinic/list")


      } else {
          console.log('error submit!', fields)
      }
  })
}


</script>

<style scoped lang="scss">
.input-width {
  width: 360px;
}

.avatar-uploader .avatar {
  width: 90px;
  height: 90px;
  display: block;
}

</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  text-align: center;
}
</style>